package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Employee;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: zhaoss
 * @Date: 2023/4/29 - 04 - 29 - 17:59
 * @Description: com.sky.service.impl
 * @version: 1.0
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 新增菜品
     *
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public Result save(DishDTO dishDTO) {
        //非空判断
        if (dishMapper.getByName(dishDTO.getName()) != null) {
            return Result.error(MessageConstant.NAME_REPEAT);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //向菜品表插入1条数据
        dishMapper.save(dish);

        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);//后绪步骤实现
        }

        return Result.success(flavors);
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public Result page(DishPageQueryDTO dto) {
        if (dto.getPage()==null){
            dto.setPage(0);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(5);
        }
        //分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //调用dao
        Page<DishVO> page = dishMapper.page(dto);

        long total = page.getTotal();
        List<DishVO> result = page.getResult();
        for (DishVO dishVO : result) {
            //口味表
            List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(dishVO.getId());
            dishVO.setFlavors(dishFlavorList);
            Category category = categoryMapper.getById(dishVO.getCategoryId());
            dishVO.setCategoryName(category.getName());
        }


        PageResult pageResult = new PageResult(total,result);
        return Result.success(pageResult);
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result delete(List<Long> ids) {
        //非空判断
        if (ids == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

//        - setmeal_dish表为菜品和套餐关联的中间表。
//        - 若删除的菜品数据关联着某个套餐，此时，删除失败。
//        - 若要删除套餐关联的菜品数据，先解除两者关联，再对菜品进行删除。
        List<Long> setmealDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealDishIds!=null && setmealDishIds.size()>0){
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //查询当前菜品是否在起售状态，如果是则不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus()== StatusConstant.ENABLE){
                return Result.error(MessageConstant.DISH_ON_SALE);
            }
        }
        //        - 在dish表中删除菜品基本数据时，同时，也要把关联在dish_flavor表中的数据一块删除。
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);
        return Result.success("删除成功");
    }

    /**
     * 通过id单一查询
     *
     * @param id
     * @return
     */
    @Override
    public Result getByid(Long id) {
        //非空判断
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        //根据dishId查口味表
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(id);
        dishVO.setFlavors(dishFlavorList);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result pudataDish(DishDTO dto) {
        //非空判断
        if (dto.getId() == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        //修改菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.updateDishById(dish);
        //删除口味
        dishFlavorMapper.deleteDishFlavor(Arrays.asList(dto.getId()));
        //新增口味
        List<DishFlavor> flavorList = dto.getFlavors();
        if (flavorList!=null && flavorList.size()>0) {
            flavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
        }

        dishFlavorMapper.insertBatch(flavorList);


        return Result.success("修改成功");
    }

    /**
     * 修改出售状态
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result updateDishStatus(Integer status, Long id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);

        dishMapper.updateDishById(dish);

        return Result.success("修改成功");
    }

    /**
     * CategoryId单一查询
     *
     * @param categoryId
     * @return
     */
    @Override
    public Result getByCategoryId(Long categoryId) {
        if (categoryId == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        List<Dish> dishList = dishMapper.getByCategoryId2(categoryId);

        return Result.success(dishList);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {

        List<Dish> dishList = dishMapper.getByCategoryId2(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
